package the.broccoli.uc.service;

import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.wisteria.framework.util.DateUtils;
import the.broccoli.setting.service.IParamsService;
import the.broccoli.uc.entity.TokenDO;
import the.broccoli.uc.mapper.TokenMapper;
import the.broccoli.uc.service.dto.TokenDTO;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * 登录令牌服务类
 */
@Service
public class TokenService {

    @Resource
    private TokenMapper tokenMapper;

    @Resource
    private IParamsService paramsService;

    /**
     * 创建新的令牌
     * @param tenantId  租户ID
     * @param userId    用户ID
     * @param content   内容
     */
    public TokenDTO newToken(Integer tenantId, String userId, String content) {
        TokenDO tokenInfo = new TokenDO();
        tokenInfo.setTenantId(tenantId);
        tokenInfo.setUserId(userId);
        tokenInfo.setContent(content);
        tokenInfo.setLoginTime(new Date());
        tokenInfo.setExpireTime(DateUtils.toDate(calcExpireTime(tenantId)));
        tokenInfo.setCreatedTime(new Date());
        tokenInfo.setModifiedTime(new Date());
        if (tokenMapper.insert(tokenInfo) > 0) {
            TokenDTO dto = new TokenDTO();
            dto.setToken(tokenInfo.getId());
            dto.setTenantId(tokenInfo.getTenantId());
            dto.setUserId(tokenInfo.getUserId());
            dto.setExpireTime(tokenInfo.getExpireTime());
            dto.setContent(tokenInfo.getContent());
            return dto;
        }
        return null;
    }

    /**
     * 获取令牌对应的内容
     * @param token 令牌
     */
    public TokenDTO getTokenInfo(Integer token) {
        TokenDO tokenInfo = tokenMapper.selectById(token);
        if (tokenInfo == null
                || tokenInfo.getExpireTime() == null
                || LocalDateTime.now().isAfter(DateUtils.toLocalDateTime(tokenInfo.getExpireTime()))) {
            return null;
        }

        TokenDTO dto = new TokenDTO();
        dto.setToken(tokenInfo.getId());
        dto.setTenantId(tokenInfo.getTenantId());
        dto.setUserId(tokenInfo.getUserId());
        dto.setExpireTime(tokenInfo.getExpireTime());
        dto.setContent(tokenInfo.getContent());
        return dto;
    }

    /**
     * 计算令牌失效时间
     */
    private LocalDateTime calcExpireTime(Integer tenantId) {
        // 单位分钟
        int expireMinute = 60 * 24 * 7;
        String loginExpire = paramsService.getValue(tenantId, "wist.auth.token.expire");
        if (StringUtils.hasText(loginExpire)) {
            expireMinute = Integer.parseInt(loginExpire);
        }
        return LocalDateTime.now().plusMinutes(expireMinute);
    }

}
